<template>
  <el-card>
    <div slot="header"><span>个人中心</span></div>
    <div>管理员ID:{{ userInfo.id }}</div>
    <el-divider></el-divider>
    <div>账号:{{ userInfo.account }}</div>
    <el-divider></el-divider>
    <div>用户组:{{ userInfo.userGroup }}</div>
    <el-divider></el-divider>
    <div>创建时间:{{ userInfo.ctime | formatYMD }}</div>
    <el-divider></el-divider>
    <div>
      管理员头像:
      <!-- 服务器地址和 -->
      <el-upload
        class="avatar-uploader"
        :action="`${API}/users/avatar_upload`"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="userInfo.imgUrl" :src="userInfo.imgUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
  </el-card>
</template>

<script>
import {updataUserAvatarRef} from '@/api/user'
import {mapState} from 'vuex'

export default {
  computed: {
    ...mapState('user', ['userInfo']),
  },
  data() {
    return {
      API: 'http://sell.h5.itsource.cn:8087',
    }
  },
  methods: {
    // 上传成功
    async handleAvatarSuccess(res) {
      let {code, msg, imgUrl} = res
      if (code === 0) {
        let res2 = await updataUserAvatarRef({
          imgUrl,
        })
        // 解构数据
        let {code, msg} = res2.data
        if (code === 0) {
          this.$router.go(0)
        }
      }
    },
    // 上传文件之前
    beforeAvatarUpload(file) {
      const isJPG = /png|jpeg/.test(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是PNG JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
  },
}
</script>

<style lang="scss" scoped>
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-top: 10px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
